package com.example.myapplication

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.MultiGridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.RecycleViewDragLayoutBinding
import java.util.Collections

/**
 * Create by Tanzhenxing on 2025/10/24.
 * Description:
 */
class RecycleViewDragActivity : AppCompatActivity() {

    companion object {
        enum class CardType{
            ONE,
            TWO,
        }

        fun getCardType(list: List<Any>) = if (list.size < 3) CardType.ONE else CardType.TWO
    }
    private val binding by lazy { RecycleViewDragLayoutBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        val list = mutableListOf<Int>()
        for (i in 0 until 2) {
            if (i % 3 == 0) {
                list.add(getColor(android.R.color.holo_red_dark))
            } else if (i % 3 == 1) {
                list.add(getColor(android.R.color.holo_blue_light))
            } else {
                list.add(getColor(android.R.color.holo_purple))
            }
        }
        val picAdapter = PicAdapter(this, list)
        Log.e("tanzhenxing", "list.size=${list.size}")
        binding.rvPicture.adapter = picAdapter
        val gridLayoutManager = MultiGridLayoutManager(this, MultiGridLayoutManager.SpanSize(4, 4))
        // Step 2: 设置 SpanSizeLookup，控制某个 item 占两列
        gridLayoutManager.spanSizeLookup = object : MultiGridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): MultiGridLayoutManager.SpanSize? {
                if (list.size == 1) {
                    return MultiGridLayoutManager.SpanSize(4, 4)
                }
                if (list.size == 2) {
                    return MultiGridLayoutManager.SpanSize(2, 4)
                }
                if (list.size == 3) {
                    if (position == 2) {
                        return MultiGridLayoutManager.SpanSize(2, 4)
                    }
                }
                return MultiGridLayoutManager.SpanSize(2, 2)
            }
        }

        binding.rvPicture.layoutManager = gridLayoutManager
        binding.rvPicture.isNestedScrollingEnabled = true
        val myItemTouchHelper = ItemTouchHelper(MyItemTouchHelper(list, picAdapter))
        myItemTouchHelper.attachToRecyclerView(binding.rvPicture)
    }

    class MyItemTouchHelper(val listData: List<Int>, val adapter: PicAdapter) : ItemTouchHelper.Callback() {
        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            val dragFlags =
                ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
            val swipeFlags = 0
            return makeMovementFlags(dragFlags, swipeFlags)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            recyclerView.parent.requestDisallowInterceptTouchEvent(true);
            //得到当拖拽的viewHolder的Position
            val fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            val toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (i in  fromPosition until  toPosition) {
                    Collections.swap(listData, i, i + 1);
                }
            } else {
                for (i in fromPosition downTo toPosition + 1) {
                    Collections.swap(listData, i, i - 1);
                }
            }
            adapter.notifyItemMoved(fromPosition, toPosition);
            Log.d("dddd", " fromPosition = $fromPosition toPosition$toPosition");
            return true
        }

        override fun onSwiped(
            viewHolder: RecyclerView.ViewHolder,
            direction: Int
        ) {
        }

        override fun isItemViewSwipeEnabled(): Boolean {
            return false
        }

        override fun isLongPressDragEnabled(): Boolean {
            return listData.size > 1
        }
    }

    class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
       val ivPic = itemView.findViewById<ImageView>(R.id.iv_picture)
    }
    class PicAdapter(val context: Context, val list: List<Int>) : RecyclerView.Adapter<ViewHolder>() {
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): ViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item_pic, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(
            holder: ViewHolder,
            position: Int
        ) {
            when(getCardType(list)) {
                CardType.ONE -> {
                    holder.itemView.layoutParams?.let { params ->
                        params.width = ViewGroup.LayoutParams.MATCH_PARENT
                        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
                        holder.itemView.layoutParams = params
                    }
                    holder.ivPic.layoutParams?.let { params ->
                        params.height = getScreenWidth(context)
                        holder.ivPic.layoutParams = params
                    }
                }
                CardType.TWO -> {
                    holder.itemView.layoutParams?.let { params ->
                        params.width = getScreenWidth(context) / 2
                        params.height = getScreenWidth(context) / 2
                        holder.itemView.layoutParams = params
                    }
                    holder.ivPic.layoutParams?.let { params ->
                        params.height = ViewGroup.LayoutParams.MATCH_PARENT
                        holder.ivPic.layoutParams = params
                    }
                }
            }
            holder.ivPic.setBackgroundColor(list[position])
        }

        override fun getItemCount(): Int {
            return list.size
        }
    }
}